package com.acme.bankapp.domain.bank;

import com.acme.bankapp.domain.exceptions.ClientExistsException;
import com.acme.bankapp.service.bank.ClientRegistrationListener;

import java.io.Serializable;
import java.util.Date;

/**
 * Created by zurdan on 14.11.14.
 * E-mail: Zurdanium@gmail.com
 */
public class Bank implements Serializable {
    private final Client[] clients = new Client[10];
    private int clientsCount = 0;
    private ClientRegistrationListener[] listeners = new ClientRegistrationListener[10];
    private int listenersCount = 0;

    public Bank() {
        addListener(new DebugListener());
    }

    public void addClient(Client client) throws ClientExistsException {
        if (clientsCount < 10) {
            for (int i = 0; i < clientsCount; i++) {
                if (client.getSalutation().equals(clients[i].getSalutation())) {
                    throw new ClientExistsException("Client already exists: " + client.getSalutation());
                }
            }
            clients[clientsCount++] = client;
            for (int i = 0; i < listenersCount; i++) {
                listeners[i].onClientAdded(client);
            }
        } else {
            System.err.println("Too many clients"); //Need collections.
        }
    }

    public void addListener(ClientRegistrationListener listener) {
        if (listenersCount < 10) {
            listeners[listenersCount++] = listener;
        } else {
            System.err.println("Too many listeners");
        }
    }

    public Client[] getClients() {
        return clients;
    }

    public int getClientsCount() {
        return clientsCount;
    }

    private class DebugListener implements ClientRegistrationListener {

        @Override
        public void onClientAdded(final Client client) {
            System.out.println("debug: " + client.getSalutation() + " - " + new Date());
        }
    }
}
